package com.leps.nq.bu.controller;

import cn.hutool.core.util.StrUtil;
import com.leps.nq.bu.entity.BuArea;
import com.leps.nq.bu.service.IBuAreaService;
import com.leps.nq.bu.vo.AreaQueryModel;
import com.leps.nq.bu.vo.AreaVo;
import com.leps.nq.common.aspect.Log;
import com.leps.nq.common.enums.BusinessType;
import com.leps.nq.common.vo.PageVo;
import com.leps.nq.common.vo.R;
import com.leps.nq.common.vo.RBuilder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 区块表 前端控制器
 * </p>
 *
 * @author hex
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/bu/bu-area")
@Api(tags = "区块管理")
public class BuAreaController {
    @Autowired
    private IBuAreaService areaService;

    @GetMapping("/listForSelect")
    public R<List<BuArea>> forSelect(Integer custId) {
        List<BuArea> list = this.areaService.listForSelect(custId);
        return RBuilder.ok(list);
    }

    @GetMapping
    @ApiOperation("区块列表")
    public R<PageVo<AreaVo>> list(AreaQueryModel queryModel) {
        PageVo<AreaVo> pageVo = this.areaService.pageByQueryModel(queryModel);
        return RBuilder.ok(pageVo);
    }

    @GetMapping("/{areaId}")
    @ApiOperation("根据id查询区块信息")
    public R<BuArea> getById(@PathVariable Integer areaId) {
        return RBuilder.ok(this.areaService.getById(areaId));
    }

    @PostMapping
    @ApiOperation("添加区块")
    @Log(title = "区块", businessType = BusinessType.INSERT)
    public R<?> save(@RequestBody BuArea area) {
        String areaName = area.getAreaName();
        Long count = this.areaService.lambdaQuery().eq(BuArea::getAreaName, areaName).count();
        if (count > 0) {
            String msg = StrUtil.format("系统中已存在 [ {} ] 这个区块，请不要重复添加。", areaName);
            throw new RuntimeException(msg);
        }
        boolean b = this.areaService.save(area);
        return RBuilder.ofBoolean(b);
    }

    @PutMapping
    @ApiOperation("更新区块")
    @Log(title = "区块", businessType = BusinessType.UPDATE)
    public R<?> update(@RequestBody BuArea area) {
        boolean b = this.areaService.updateById(area);
        return RBuilder.ofBoolean(b);
    }

    @DeleteMapping
    @ApiOperation("删除区块")
    @Log(title = "区块", businessType = BusinessType.DELETE)
    public R<?> remove(@RequestBody List<Integer> areaIds) {
        boolean b = this.areaService.removeBatchByIds(areaIds);
        return RBuilder.ofBoolean(b);
    }
}
